<script lang="ts" setup>
// 定义配置项的类型

import { useVbenModal } from '@vben/common-ui';
import { cloneDeep } from '@vben/utils';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { formatValues, generateFormSchema } from '#/utils';

const state: {
  attributes: any;
} = reactive({
  attributes: [],
});

const [AttributesForm, AttributesFormApi] = useVbenForm({
  layout: 'vertical',
  showDefaultActions: false,
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    }, 
    labelClass: 'w-2/6',
  },
  // 提交函数
  handleSubmit: (values) => {
    const formApiState = AttributesFormApi.getState();
    const formApiStateSchema = formApiState?.schema || [];
    state.attributes = formatValues(formApiStateSchema, values);
  },
  wrapperClass: 'grid-cols-1',
});

const [Modal, ModalApi] = useVbenModal({
  fullscreenButton: false,
  onBeforeClose() {
    AttributesFormApi.setState({ schema: [] });
  },
  async onConfirm() {
    await AttributesFormApi.validateAndSubmitForm();
    ModalApi.setData({
      attributes: cloneDeep(state.attributes),
      isUpdata: true,
    });
    ModalApi.close();
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) return;

    const modalData: any = ModalApi.getData();
    if (modalData) {
      try {
        const { schema, values } = generateFormSchema(modalData.module);
        AttributesFormApi.setState({ schema });
        AttributesFormApi.setValues(values);
      } catch (error) {
        console.error('加载配置失败', error);
        message.error('加载配置失败，请重试');
      }
    }
  },
});
</script>

<template>
  <Modal>
    <AttributesForm />
  </Modal>
</template>
